//
//  PhotoBrowserCtr.swift
//  sinaDemo
//
//  Created by Xueming on 2021/3/29.
//

import UIKit
import Photos
import SDWebImage
private let photoBrowserCellID = "photoBrowserCellID"

class XMPhotoBrowserCtr: UIViewController {
    var pageScrollCallBack:((_ page:Int)->())?
    lazy var pageView:UIPageControl = UIPageControl.init(frame: CGRect(x: 0, y: kScreenHeight / 8 * 6.5, width: kScreenWidth, height: 50)).then({
        $0.numberOfPages = self.picUrls.count
        $0.currentPage = self.index.row
        $0.backgroundColor = UIColor.clear
        $0.isUserInteractionEnabled = false
    })
    
    lazy var collectionView:UICollectionView = UICollectionView.init(frame:CGRect(x: 0, y: 0, width: kScreenWidth + 20, height: kScreenHeight),collectionViewLayout: photoBrowserLayout()).then({
        $0.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(self.dismissCtr)))
    })
    lazy var closeBtn:UIButton = UIButton.init(title: "关 闭", font: 14, backColor: .gray).then {
        $0.top = kScreenHeight - 100
        $0.left = 20
        $0.width = 80
        $0.height = 35
        $0.addTarget(self, action: #selector(self.closeBtnClick), for: .touchUpInside)
    }
    lazy var saveBtn:UIButton = UIButton.init(title: "保 存", font: 14, backColor: .gray).then {
        $0.width = 80
        $0.right = kScreenWidth - 20
        $0.height = 35
        $0.top = closeBtn.top
        $0.addTarget(self, action: #selector(self.saveBtnClick), for: .touchUpInside)
    }
    
    var picUrls:[String]!
    var index:NSIndexPath!
    var smallImages:[String]!
    
    init(picUrls:[String],index:NSIndexPath) {
        super.init(nibName: nil, bundle: nil)
        self.picUrls = picUrls
        self.index = index
    }
    init(smallImages:[String],picUrls:[String],index:NSIndexPath) {
        super.init(nibName: nil, bundle: nil)
        self.smallImages = smallImages
        self.picUrls = picUrls
        self.index = index
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        view.backgroundColor = .black
        NotificationCenter.default.addObserver(self, selector: #selector(self.dismissCtr), name: NSNotification.Name.init(ClosePhotoBrowserCtrNotification), object: nil)
    }
    override func loadView() {
        super.loadView()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
        print("XMPhotoBrowserCtr deinit")
    }
    private func setUpUI(){
        
        collectionView.register(PhotoBrowserCell.self, forCellWithReuseIdentifier: photoBrowserCellID)
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .black
        view.addSubview(pageView)
        collectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: false)
        
    }
    @objc private func dismissCtr(){
        dismiss(animated: true, completion: nil)
    }
    
}
extension XMPhotoBrowserCtr:UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.picUrls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoBrowserCellID, for: indexPath) as! PhotoBrowserCell
        cell.smallImag = self.smallImages[indexPath.item]
        cell.url = self.picUrls[indexPath.item]
        return cell
    }
    //    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    //        dismiss(animated: true, completion: nil)
    //    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = floor((scrollView.contentOffset.x - self.view.bounds.width/2)/self.view.bounds.width + 1)
        self.pageView.currentPage = Int(page)
        pageScrollCallBack?(self.pageView.currentPage)
    }
    
}
// MARK: - 点击事件

extension XMPhotoBrowserCtr{
    @objc private func closeBtnClick(){
        dismiss(animated: true, completion: nil)
    }
    @objc private func saveBtnClick(){
        let cell = collectionView.visibleCells.last as! PhotoBrowserCell
        let image = cell.zoomView.imageView.image
        if image != nil {
            UIImageWriteToSavedPhotosAlbum(image!, self, #selector(saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
        }
        
    }
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil{
            print("保存失败")
            
            let status = PHPhotoLibrary.authorizationStatus()
            if (status == .authorized) {
                //                savePhoto(value: "1")
            }
            else if (status == .restricted || status == .denied) {
                let alerCtr = UIAlertController.init(title: "提示", message: "请去-> [设置 - 隐私 - 相册] 打开访问开关", preferredStyle: .actionSheet)
                let sureAction = UIAlertAction.init(title: "确定", style: .default) { (action) in
                    let urlObj = URL(string:UIApplication.openSettingsURLString)
                    if #available(iOS 10.0, *) {
                        UIApplication.shared.open(urlObj! as URL, options: [ : ], completionHandler: { Success in
                            
                        })
                        
                    } else {
                            UIApplication.shared.openURL(urlObj!)
                    }
                }
                alerCtr.addAction(sureAction)
                self.present(alerCtr, animated: true, completion: nil)
            
            }
            else if (status == .notDetermined) {//首次使用
                PHPhotoLibrary.requestAuthorization({ (firstStatus) in
                    let isTrue = (firstStatus == .authorized)
                    if isTrue {
                        print("首次允许")
                    
                    } else {
                        print("首次不允许")
                
                    }
                })
            }
            
        }else{
            print("保存成功")
        }
    }
}
class photoBrowserLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        itemSize = collectionView!.frame.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.alwaysBounceHorizontal = true
    }
}


class PhotoBrowserCell: UICollectionViewCell {
    lazy var progressView:XMCircelProgressView = XMCircelProgressView.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50)).then({
        $0.center = kWindow!.center
    })
    var smallImag:String? = nil{
        didSet{
            let defaultImage = SDImageCache.shared.imageFromDiskCache(forKey: smallImag)
            self.zoomView.imageView.image = defaultImage
        }
    }
    var url:String? = nil {
        didSet{
            guard let url = url else {
                return
            }
            
            self.progressView.isHidden = false
            self.zoomView.imageView.sd_setImage(with: URL.init(string: url), placeholderImage: self.zoomView.imageView.image, options: []) { (current, all, url) in
                self.progressView.progress = current.floatValue / all.floatValue
            } completed: { (image, error, cacheType, url) in
                self.progressView.isHidden = true
                guard let image = image else{
                    return
                }
                self.zoomView.image = image
            }
        }
        
    }
    
    lazy var zoomView:XMZoomView =  XMZoomView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), ImageOriginFrame: CGRect.zero, image: nil)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    deinit {
        //        print("PhotoBrowserCell deinit")
    }
    private func setUpUI(){
        contentView.backgroundColor = .black
        
        contentView.addSubview(zoomView)
        
        contentView.addSubview(progressView)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
